import {
	Toast
} from 'vant';
import store from '@/store/index'
var heartClearInterval;
export const initSocketMiddleware = (params = {}) => {
	window.middlewareSocket = {
		socket: new WebSocket(myConfig.middlewareSocketURL), //socket实例
		params: {}, //存的请求参数
		data: {}, //socket返回的参数
	}
	middlewareSocket.socket.onopen = () => {
		console.log("middleware服务[Socket连接成功]");
		sendSocket({
			RndCode: -2,
			Data: {
				"ID": store.state.deviceInfo.sn,
				"IP": "",
				"MAC": store.state.deviceInfo.sn,
				"TYPE": 0,
				"UNIQUE_KEY": "",
				"VERSION": "1.0.0.1"
			}
		})
		clearInterval(heartClearInterval);
		heartClearInterval = setInterval(() => {
			// console.log('发送心跳')
			sendSocket({
				RndCode: -2,
				Data: {
					"tradeCode": 'heartbeat',
					"code": "0",
					"msg": "客户端心跳",
					"data": {
						"recipestatus": '0'
					}
				}
			});
		}, 20000)
		params.success && params.success();
		store.commit('setMiddlewareState', 'success')
	};
	middlewareSocket.socket.onerror = e => {
		console.log(e, "socket连接失败");
		params.fail && params.fail();
		store.commit('setMiddlewareState', 'fail')
	};
	middlewareSocket.socket.onclose = e => {
		//重连
		setTimeout(() => {
			console.log('socket重连')
			initSocketMiddleware();
		}, 5000)
	};
	middlewareSocket.socket.onmessage = res => {
		let data = JSON.parse(res.data);
		let tradeCode = data.Data.tradeCode;
		let RndCode = data.RndCode;
		// window.middlewareSocket.data[tradeCode]=data.Data;
		console.log('\x1B[41m%s\x1B[0m', '------', `middlewareSocket收到[${tradeCode||''}]:`, JSON.stringify(
			data))
		if (tradeCode) {
			store.commit('setMiddlewareData', data);
		}else{
			//需要回复一下socket服务器
			// sendSocket(data)
		}
	};
};
export const closeSocket = () => {
	if (middlewareSocket.socket) {
		middlewareSocket.socket.close();
	}
};
export const sendSocket = (params) => {
	window.middlewareSocket.params[params.Data.tradeCode] = params;

	middlewareSocket.socket.send(JSON.stringify(params));
	if(params.Data.tradeCode!='heartbeat'){
		console.log('\x1B[40m%s\x1B[0m', '------', `middlewareSocket发送[${params.Data.tradeCode}]:`, JSON.stringify(
			params))
	}
};

export default {
	
}